package org.example.medicalstaff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.his.common.api.CommonResponse;
import org.example.medicalstaff.entity.CheckApply;
import org.example.medicalstaff.entity.CheckRelation;
import org.example.medicalstaff.entity.CheckTemplate;
import org.example.medicalstaff.entity.FmedItem;
import org.example.medicalstaff.mapper.CheckApplyMapper;
import org.example.medicalstaff.mapper.CheckRelationMapper;
import org.example.medicalstaff.mapper.CheckTemplateMapper;
import org.example.medicalstaff.mapper.FmedItemMapper;
import org.example.medicalstaff.service.PatientClientService;
import org.example.medicalstaff.service.PatientItemService;
import org.example.medicalstaff.utils.DateStringFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class PatientItemServiceImpl implements PatientItemService{

    @Autowired
    private CheckApplyMapper checkApplyMapper;
    @Autowired
    private CheckTemplateMapper checkTemplateMapper;
    @Autowired
    private CheckRelationMapper checkRelationMapper;
    @Autowired
    private FmedItemMapper fmedItemMapper;
    @Autowired
    private CheckApply checkApply;
    @Autowired
    private CheckTemplate checkTemplate;
    @Autowired
    private CheckRelation checkRelation;
    @Autowired
    private FmedItem fmedItem;

    /**
     * API1 新增检查项目
     */
    public CommonResponse<String> new_check(
            int MedicalID,
            int RegistID,
            int ItemID,
            String Name,
            String Objective,
            String Position,
            int IsUrgent,
            int Num,
            int State,
            int RecordType,
            int DoctorID
    ){
        //State=1;
        CheckApply checkApply = new CheckApply();
        checkApply.setMedicalID(MedicalID);
        checkApply.setRegistID(RegistID);
        checkApply.setItemID(ItemID);
        checkApply.setName(Name);
        checkApply.setObjective(Objective);
        checkApply.setPosition(Position);
        checkApply.setIsUrgent(IsUrgent);
        checkApply.setNum(Num);
        checkApply.setState(State);
        checkApply.setRecordType(RecordType);
        checkApply.setDoctorID(DoctorID);
        //设置当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        String pattern = "yyyy-MM-dd HH:mm:ss";
        Date date = DateStringFormat.parseDateTimeString(formattedDateTime,pattern);
        checkApply.setCreationTime(date);
        int result = checkApplyMapper.insert(checkApply);
        if (result == 0){
            return CommonResponse.createForError("新增检查项目失败");
        }else{
            return CommonResponse.createForSuccess("新增检查项目成功");
        }
    }

    /**
     * API4 根据模板和模板明细来新增检查项目
     */
    public CommonResponse<String> new_check_by_template(
            int MedicalID,
            int RegistID,
            int CheckTempID,
            String Objective,
            String Position,
            int IsUrgent,
            int Num,
            int State,
            int RecordType,
            int DoctorID
    ){
        //1.先根据check_temp_id获取模板明细的数量，根据数量生成对应的申请表，
        //2.然后把模板明细的项目ID和项目名称覆盖申请表中的对应信息。
        QueryWrapper<CheckRelation> checkRelationQueryWrapper = new QueryWrapper<>();
        checkRelationQueryWrapper.eq("CheckTempID",CheckTempID);
        List<CheckRelation> checkRelationList = checkRelationMapper.selectList(checkRelationQueryWrapper);
        int ListLength = checkRelationList.size();
        //如果模板ID给错了，根本不会进到循环去
        //所以这里要判断一下List的长度
        if (ListLength == 0){
            return CommonResponse.createForError("根据模板新增检查项目失败");
        }
        for (int i = 0; i < ListLength; i++) {
            //构建对应数量的申请表
            checkRelation = checkRelationList.get(i);
            CheckApply checkApply1 = new CheckApply();
            checkApply1.setMedicalID(MedicalID);
            checkApply1.setRegistID(RegistID);
            checkApply1.setItemID(checkRelation.getCheckProjID());//项目ID的设置
            //根据项目ID找名字，下午写，这里不确定对不对，需要测试一下接口。
            QueryWrapper<FmedItem> fmedItemQueryWrapper = new QueryWrapper<>();
            fmedItemQueryWrapper.select("ItemName").eq("ID",checkApply1.getItemID());
            fmedItem = fmedItemMapper.selectOne(fmedItemQueryWrapper);
            checkApply1.setName(fmedItem.getItemName());
            //补齐其他属性
            checkApply1.setObjective(Objective);
            checkApply1.setPosition(Position);
            checkApply1.setIsUrgent(IsUrgent);
            checkApply1.setNum(Num);
            checkApply1.setState(State);
            checkApply1.setRecordType(RecordType);
            checkApply1.setDoctorID(DoctorID);
            //插入数据库中去
            int result = checkApplyMapper.insert(checkApply1);
            if (result == 0){
                return CommonResponse.createForError("根据模板新增检查项目失败");
            }
        }
            return CommonResponse.createForSuccess("根据模板新增检查项目成功");
    }


    /**
     * API7 删除未开立项目
     */
    public CommonResponse<String> del_no_init_pro(
            int MedicalID,
            int RegistID,
            int ItemID,
            int DoctorID
    ){
        QueryWrapper<CheckApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("ItemID",ItemID);
        queryWrapper.eq("DoctorID",DoctorID);
        checkApply = checkApplyMapper.selectOne(queryWrapper);
        if (checkApply.getState() != 1){
            //说明不是暂存状态
            return CommonResponse.createForError("删除未开立项目失败，不是暂存状态！");
        }
        int result = checkApplyMapper.delete(queryWrapper);
        if (result == 0){
            return CommonResponse.createForError("删除未开立项目失败");
        }else {
            return CommonResponse.createForSuccess("删除未开立项目成功");
        }
    }

    /**
     * API8 开立项目
     */
    public CommonResponse<String> init_pro(
            int MedicalID,
            int RegistID,
            int ItemID,
            int DoctorID
    ){
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        //这里要把时间转换为Date再存入
        //设置时间格式
        String pattern = "yyyy-MM-dd HH:mm:ss";
        Date date = DateStringFormat.parseDateTimeString(formattedDateTime,pattern);
        System.out.println("Current datetime: " + formattedDateTime);
        UpdateWrapper<CheckApply> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("State",2)
                .set("DoctorID",DoctorID)
                .set("CreationTime",date)
                .eq("MedicalID",MedicalID)
                .eq("RegistID",RegistID)
                .eq("ItemID",ItemID);
        int result = checkApplyMapper.update(null,updateWrapper);
        if (result == 0){
            return CommonResponse.createForError("开立项目失败");
        }else{
            return CommonResponse.createForSuccess("开立项目成功");
        }
    }

    /**
     * API9 作废项目
     */
    public CommonResponse<String> repeal_init_pro(
            int MedicalID,
            int RegistID,
            int ItemID,
            int DoctorID
    ){
        UpdateWrapper<CheckApply> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("State",0)
                .eq("MedicalID",MedicalID)
                .eq("RegistID",RegistID)
                .eq("ItemID",ItemID)
                .eq("DoctorID",DoctorID);
        int result = checkApplyMapper.update(null,updateWrapper);
        if (result == 0){
            return CommonResponse.createForError("作废项目失败");
        }else{
            return CommonResponse.createForSuccess("作废项目成功");
        }
    }
}
